/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import Fachada.Fachada;
import classes.Fornecedor;
import erro.ConexaoException;
import erro.ConsultaException;
import erro.DaoException;
import erro.GeralException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Alcidelio
 */
public class telaPesquisarFornecedor extends javax.swing.JFrame {

    private static Fachada f;
    String cnpj;
    /**
     * Creates new form telaPesquisarFornecedor
     */
    public telaPesquisarFornecedor() {
        initComponents();
        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        ButtonAltFornec = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TableFornec = new javax.swing.JTable();
        ButtonCancelar = new javax.swing.JButton();
        jButtonListarFornec = new javax.swing.JButton();
        jButtonPesqFornec = new javax.swing.JButton();
        txtBoxPesqCNPJFornec = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("CNPJ:");

        ButtonAltFornec.setText("ALTERAR");
        ButtonAltFornec.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonAltFornecActionPerformed(evt);
            }
        });

        TableFornec.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "CNPJ", "Nome", "Telefone"
            }
        ));
        TableFornec.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableFornecMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(TableFornec);

        ButtonCancelar.setText("CANCELAR");
        ButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonCancelarActionPerformed(evt);
            }
        });

        jButtonListarFornec.setText("ATUALIZAR");
        jButtonListarFornec.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonListarFornecActionPerformed(evt);
            }
        });

        jButtonPesqFornec.setText("PESQUISAR");
        jButtonPesqFornec.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPesqFornecActionPerformed(evt);
            }
        });

        try {
            txtBoxPesqCNPJFornec.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.###.###/####-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel2.setText("Pesquisar Fornecedor");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(56, 56, 56)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(62, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(75, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addGap(72, 72, 72))
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtBoxPesqCNPJFornec, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonPesqFornec, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(ButtonAltFornec, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonListarFornec)
                        .addGap(18, 18, 18)
                        .addComponent(ButtonCancelar)
                        .addGap(7, 7, 7))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(41, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtBoxPesqCNPJFornec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonPesqFornec, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonListarFornec, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
                    .addComponent(ButtonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ButtonAltFornec, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ButtonAltFornecActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonAltFornecActionPerformed

        telaAlterarFornecedor alteraFornec = new telaAlterarFornecedor();
        alteraFornec.setVisible(true);
        Fornecedor fornec = new Fornecedor();
        cnpj = txtBoxPesqCNPJFornec.getText().replace(".", "");
        cnpj = cnpj.replace(".", "");
        cnpj = cnpj.replace("/", "");
        cnpj = cnpj.replace("-", "");
        cnpj = cnpj.replace(" ", "");
        f = Fachada.getInstancia();
        fornec.setCnpjFornecedor(cnpj);

        try {
            f.pesquisarFornec(fornec);
        } catch (GeralException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (DaoException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        if (fornec.getNomeFornecedor() == null) {
            alteraFornec.setVisible(false);
            alteraFornec.dispose();
        } else {
            alteraFornec.LabelCodFornec.setText(Integer.toString(fornec.getCodFornecedor()));
            alteraFornec.txtBoxNOMEFornec.setText(fornec.getNomeFornecedor());
            alteraFornec.txtBoxCNPJfornec.setText(fornec.getCnpjFornecedor());
            alteraFornec.txtBoxFONEFornec.setText(fornec.getFoneFornecedor());
        }
    }//GEN-LAST:event_ButtonAltFornecActionPerformed

    private void TableFornecMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableFornecMouseClicked
        
        int x = TableFornec.getSelectedRow();
        int y = TableFornec.getSelectedColumn();

        //Se o clique for duplo
        if (evt.getClickCount() == 1) {
            if (evt.getButton() == evt.BUTTON1) {//E o botão for o esquerdo
                txtBoxPesqCNPJFornec.setText((String) TableFornec.getValueAt(x, 0));

            }
        }
    }//GEN-LAST:event_TableFornecMouseClicked

    private void ButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonCancelarActionPerformed
        telaPesquisarFornecedor tlpesqfornec = new telaPesquisarFornecedor();
        int i = JOptionPane.showConfirmDialog(null, "Deseja realmente Cancelar?", "Cancelar", JOptionPane.YES_NO_OPTION);
        if (i == JOptionPane.YES_OPTION) {
            telaPesquisarFornecedor.this.setVisible(false);
            tlpesqfornec.dispose();
        } else {
            repaint();
        }
    }//GEN-LAST:event_ButtonCancelarActionPerformed

    private void jButtonListarFornecActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonListarFornecActionPerformed
       listarTabela();
       txtBoxPesqCNPJFornec.setText("");
    }//GEN-LAST:event_jButtonListarFornecActionPerformed

    private void jButtonPesqFornecActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPesqFornecActionPerformed
        TableFornec.getColumnModel().getColumn(0).setPreferredWidth(150);
        TableFornec.getColumnModel().getColumn(1).setPreferredWidth(300);
        TableFornec.getColumnModel().getColumn(2).setPreferredWidth(130);
        DefaultTableModel modelo = (DefaultTableModel) TableFornec.getModel();
        modelo.setNumRows(0);
        f = Fachada.getInstancia();
        Fornecedor fornec = new Fornecedor();
        cnpj = txtBoxPesqCNPJFornec.getText().replace(".", "");
        cnpj = cnpj.replace(" ", "");
        cnpj = cnpj.replace("/", "");
        cnpj = cnpj.replace("-", "");
        
        ArrayList<Fornecedor> lista = new ArrayList<Fornecedor>();
        try {
            fornec.setCnpjFornecedor(cnpj+ "%");
            lista = (ArrayList<Fornecedor>) f.pesquisarFornecedor(fornec);
            } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        for (int i = 0; i < lista.size(); i++) {
            modelo.addRow(new Object[]{lista.get(i).getCnpjFornecedor(), lista.get(i).getNomeFornecedor(),
                        lista.get(i).getFoneFornecedor()});
        }
        TableFornec.setModel(modelo);
    }//GEN-LAST:event_jButtonPesqFornecActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarFornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarFornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarFornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarFornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new telaPesquisarFornecedor().setVisible(true);
            }
        });
    }

    public void listarTabela(){
        TableFornec.getColumnModel().getColumn(0).setPreferredWidth(150);
        TableFornec.getColumnModel().getColumn(1).setPreferredWidth(300);
        TableFornec.getColumnModel().getColumn(2).setPreferredWidth(130);
        DefaultTableModel modelo = (DefaultTableModel) TableFornec.getModel();
        modelo.setNumRows(0);
        f = Fachada.getInstancia();
        Fornecedor fornec = new Fornecedor();
        ArrayList<Fornecedor> lista = new ArrayList<Fornecedor>();
        try {
            lista = (ArrayList<Fornecedor>) f.listar(fornec);
            } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        for (int i = 0; i < lista.size(); i++) {
            modelo.addRow(new Object[]{lista.get(i).getCnpjFornecedor(), lista.get(i).getNomeFornecedor(),
                        lista.get(i).getFoneFornecedor()});
        }
        TableFornec.setModel(modelo);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonAltFornec;
    private javax.swing.JButton ButtonCancelar;
    private javax.swing.JTable TableFornec;
    private javax.swing.JButton jButtonListarFornec;
    private javax.swing.JButton jButtonPesqFornec;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JFormattedTextField txtBoxPesqCNPJFornec;
    // End of variables declaration//GEN-END:variables
}
